package cn.itcast.order.service.impl;


import cn.itcast.order.common.OrderState;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.client.AccountClient;
import org.example.client.StorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ConditionalOnDiscoveryHealthIndicatorEnabled;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * @author 虎哥
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AccountClient accountClient;


    @Resource
    private StorageClient storageClient;

//    @Autowired
//    private UserClient userClient;


    @Override
    @Transactional
    public Long create(@Autowired(required = false) Order order) {
        int insert = orderMapper.insert(order);
//        if (insert > 0) {
//            ResponseEntity<Boolean> deduct = accountClient.deduct(order.getUserId(), order.getMoney());
//            ResponseEntity<Void> deduct1 = storageClient.deduct(order.getCommodityCode(), order.getCount());
//            if (Boolean.TRUE.equals(deduct.getBody())) {
//                return order.getId();
//            }
//        }
//        return -1L;
        return order.getId();
    }


    @Override
    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);

        // 2.查询用户
//        User user = restTemplate.getForObject("http://userservice/user/" + order.getUserId(), User.class);
//        User user = userClient.findById(order.getUserId());
//        order.setUser(user);

        // 3.返回
        return order;
    }

    @Override
    public Boolean insertOrder(Order order) {

        //添加订单
        Boolean statue = orderMapper.insertOrder(order);

//        return  statue;
        ResponseEntity<Boolean> deduct = accountClient.deduct(order.getUserId(), order.getMoney());
        Boolean body = deduct.getBody();

        ResponseEntity<Void> deduct1 = storageClient.deduct(order.getCommodityCode(), order.getCount());

        return body && statue;

//        if(body && statue) {
//            return body;
//        }else {
//            return false;
//        }

    }

    @Override
    public Boolean updateOrderState(Order order) {
        // 更新订单状态
        return orderMapper.updateOrderState(order.getId(), OrderState.getOrderState(order.getState()).nextState.get().getValue());
    }
}
